<!-- 该组件含有一个div,
  div中含有一个删除按钮，一个拖拽按钮，
  只有鼠标按下拖拽按钮才可以拖拽，拖拽其他地方无法拖拽 
-->
<template>
  <div class="draggable-box">
    <el-icon size="small" type="primary" icon="el-icon-rank" class="drag-handle" title="拖拽" draggable="true"
      @dragstart="onDragStart" 
      @dragend="onDragEnd">
      <Rank />
    </el-icon>
    <el-icon size="small" type="danger" icon="el-icon-delete" @click="handleDelete" class="delete-btn" draggable="false"
      title="删除">
      <Delete />
    </el-icon>
    {{ isVal }}

  </div>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineProps } from 'vue'
import { Rank, Delete } from '@element-plus/icons-vue';
const props = defineProps({
  //显示内容
  val: {
    type: String,
    default: ""
  },
  // 索引
  isIndex: {
    type: Number,
    default: 0
  }
})
const emit = defineEmits(['del', 'dragstart', 'dragend'])
const isVal = ref(props.val)



const onDragStart = (event: DragEvent) => {
  // 传递拖拽开始事件给父组件，携带索引
  emit('dragstart', event)
  // 必须设置拖拽数据，否则拖拽无效
  event.dataTransfer?.setData('text/plain', String(props.isIndex))
  event.dataTransfer!.effectAllowed = 'move'
}

const onDragEnd = (event: DragEvent) => {
  emit('dragend', event)
}
const handleDelete = () => {
  emit('del', props.isIndex)
}
</script>

<style scoped>
.draggable-box {
  position: absolute;
  width: 220px;
  min-height: 120px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  padding: 10px;
  user-select: none;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.drag-handle {
  cursor: move;
  margin-bottom: 10px;
  display: inline-block;
}

.delete-btn {
  position: absolute;
  top: 6px;
  right: 6px;
}
</style>
